﻿// Form1.cs
using System;
using System.Windows.Forms;

namespace BarcodeScannerApp
{
    public partial class Form1 : Form
    {
        private RawBarcodeScanner _scanner;

        public Form1()
        {
            InitializeComponent();

            // 1. 实例化扫描器，传入当前窗体句柄
            _scanner = new RawBarcodeScanner(this.Handle);

            // 2. 订阅扫描完成事件
            _scanner.BarcodeScanned += code =>
            {
                // 注意：跨线程更新 UI 时要用 Invoke
                if (txtResult.InvokeRequired)
                {
                    txtResult.Invoke(new Action(() => txtResult.Text = code));
                }
                else
                {
                    txtResult.Text = code;
                }
            };
        }

        protected override void WndProc(ref Message m)
        {
            // 只有当 _scanner 不为 null 并且它处理了 WM_INPUT，才直接 return
            if (_scanner != null && _scanner.ProcessMessage(ref m))
                return;

            base.WndProc(ref m);
        }

        private void btnToggle_Click(object sender, EventArgs e)
        {
            if (btnToggle.Text == "开始监听")
            {
                _scanner.Start();
                btnToggle.Text = "停止监听";
                txtResult.Clear();
                // **移除按钮焦点，防止扫描时误触点击**
                this.ActiveControl = null;
                this.Focus();
            }
            else
            {
                _scanner.Stop();
                btnToggle.Text = "开始监听";
                // 同样移除焦点，避免按钮保持高亮
                this.ActiveControl = null;
                this.Focus();
            }
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            _scanner?.Dispose();
            base.OnFormClosed(e);
        }
    }
}
